//
//  SelectImgUtils.m
//  laowu
//
//  Created by 尹桥印 on 15/5/10.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//

#import "SelectImgUtils.h"
#import "JTSActionSheet.h"
#import "AFNetworking.h"
#import "UploadInfo.h"
#import <MobileCoreServices/MobileCoreServices.h>


static SelectImgUtils *instance;
@interface SelectImgUtils()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong)UIImagePickerController *imagePickerController;

@end

@implementation SelectImgUtils

+(instancetype)shareInstance{
    if (!instance) {
        instance = [[SelectImgUtils alloc] init];
    }
    return instance;
}

-(void)selectImageWithCtrl:(UIViewController *)ctrl{
    JTSActionSheetTheme *theme = [JTSActionSheetTheme defaultTheme];
    theme.separatorColor = HEXColor(@"#dfdfdf");
    theme.normalButtonColor = [UIColor blackColor];
    theme.destructiveButtonColor = [UIColor blackColor];
    theme.titleColor = [UIColor blackColor];
    theme.cancelButtonColor = [UIColor blackColor];
    
    JTSActionSheetItem *buyAll = [JTSActionSheetItem itemWithTitle:@"拍照" action:^{
        //前往拍照
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
        //设置拍照时的下方的工具栏是否显示，如果需要自定义拍摄界面，则可把该工具栏隐藏
        _imagePickerController.showsCameraControls  = YES;
        [ctrl presentViewController:_imagePickerController animated:YES completion:nil];
    } isDestructive:NO];
    
    JTSActionSheetItem *deleteAll = [JTSActionSheetItem itemWithTitle:@"从手机相册选择" action:^{
        //前往手机相册
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
        [ctrl presentViewController:_imagePickerController animated:YES completion:nil];
    } isDestructive:NO];
    
    JTSActionSheetItem *cancel = [JTSActionSheetItem itemWithTitle:@"取消" action:^{
    } isDestructive:NO];
    
    JTSActionSheet *sheet = [[JTSActionSheet alloc] initWithTheme:theme
                                                            title:nil
                                                      actionItems:@[buyAll, deleteAll]
                                                       cancelItem:cancel];
    [sheet showInView:ctrl.view];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取图片裁剪的图
    UIImage* edit = [info objectForKey:UIImagePickerControllerEditedImage];
    [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
    if ([_delegate respondsToSelector:@selector(selectImgUtilsImg:)]) {
        [_delegate selectImgUtilsImg:edit];
    }else{
        [self uploadImg:edit];
    }
}

/**
 *  上传图片
 *  @param image
 */
-(void)uploadImg:(UIImage *)image{
    NSString *url = [NSString stringWithFormat:@"%@api/img/upload.json",BASE_URL];
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setObject:APP_KEY_VALUE forKey:APP_KEY_KEY];
    [param setObject:[UserDefaultsHelper stringForKey:KEY_USER_ID] forKey:@"user_id"];
    
    
    MBProgressHUD *hud = [DialogUtils showLoadingWithView:nil];
    // 1.获得请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 2.发送POST请求
    [mgr POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        [formData appendPartWithFileData:data name:@"file_data" fileName:@"status.jpg" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [hud hide:YES];
        UploadInfo *response = [[UploadInfo class] objectWithJSONData:operation.responseData];
        if (response.isSucc) {
            if ([_delegate respondsToSelector:@selector(selectImgUtilsUrl:)]) {
                [_delegate selectImgUtilsUrl:response.url];
            }
        }else{
            [DialogUtils showTipsWithView:nil String:response.msg];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [DialogUtils showTipsWithView:nil String:@"上传失败"];
        [hud hide:YES];
    }];
}

@end
